package com.meizhuo.listview.DataSaveUtil;


import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.meizhuo.listview.network_data.send_data.Register;

import java.util.ArrayList;
import java.util.List;

// 一个 SharedPreferences 只能用一次，不能做成单例模式
public class ListDataSave {
        private SharedPreferences preferences;
        private SharedPreferences.Editor editor;

        private ListDataSave(Context mContext, String preferenceName) {
            preferences = mContext.getSharedPreferences(preferenceName, mContext.MODE_PRIVATE);
            editor = preferences.edit();
        }

        /**
         * 保存List
         * @param tag
         * @param datalist
         */
        public  boolean setDataList(String tag, List<Register> datalist) {
            if (null == datalist || datalist.size() <= 0)
                return false;
            Gson gson = new Gson();
            //转换成json数据，再保存
            String strJson = gson.toJson(datalist);
            editor.clear();
            editor.putString(tag, strJson);
           return  editor.commit();
        }

    public  boolean setData(String tag, Register data) {
        if (null == data )
            return false;
        Gson gson = new Gson();
        //转换成json数据，再保存
        String strJson = gson.toJson(data);
        editor.clear();
        editor.putString(tag, strJson);
        return editor.commit();
    }

        /**
         * 获取List
         * @param tag
         * @return
         */
        public  List<Register> getDataList(String tag) {
            List<Register> datalist =new ArrayList<Register>();
            String strJson = preferences.getString(tag, null);
            if (null == strJson) {
                return datalist;
            }
            Gson gson = new Gson();
            datalist = gson.fromJson(strJson, new TypeToken<List<Register>>() {
            }.getType());
            return datalist;

        }

      public Register getData(String tag) {

      Register data = null;

        String strJson = preferences.getString(tag, null);
        if (null == strJson) {
            return data;
        }
        Gson gson = new Gson();
        data = gson.fromJson(strJson, new TypeToken<Register>(){
        }.getType());
        return data;

    }

    public static ListDataSave getInstance(Context mContext, String preferenceName){

        ListDataSave listDataSave = new ListDataSave( mContext, preferenceName);
        return listDataSave;
    }

    public void removeData(String tag){
        editor.remove(tag);
        editor.commit();
    }

    }

